<script setup lang="ts">
import http from "../../utils/http";
import { Plus, Search, Refresh, Edit, Delete } from "@element-plus/icons-vue";
import { ElMessage, type UploadProps } from "element-plus";
import { getImageUrl } from "../../utils/system";
import Config from "../../config/index";
import { computed, onMounted, ref, onBeforeUnmount, shallowRef } from "vue";
import { hasPermission } from "../../utils/system";
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { IEditorConfig } from "@wangeditor/editor";
import { IToolbarConfig } from '@wangeditor/editor'
import "@wangeditor/editor/dist/css/style.css";

const initParams = {
  pageNum: 1,
  pageSize: 10,
  name: "",
  level: "",
};

// 搜索条件
const params = ref({ ...initParams });

// 初始表单数据
const initForm = {
  name: "",
  avatar: "",
  level: "国家级",
  title: "",
  region: "",
  intro: "",
  description: "",
  categoryId: null,
};

// 表单数据
const form = ref({ ...initForm });
// 表格数据
const tableData = ref([]);
// 表格数据总数
const total = ref(0);
// 控制弹窗显示
const visible = ref(false);
// 编辑状态
const isEdit = ref(false);
// 弹窗标题
const dialogTitle = ref("");
// 分类列表
const categoryList = ref([]);
// 图片预览地址
const imageUrl = ref("");
// 上传配置
const uploadUrl = Config.baseUrl + "/file/upload";
const uploadData = {
  headers: {
    Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
  },
};
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()
const toolbarConfig: Partial<IToolbarConfig> = {} // 工具栏配置
const editorConfig: Partial<IEditorConfig> = {  // 编辑器配置
  placeholder: "请输入详细介绍...",
  MENU_CONF: {
    uploadImage: {
      server: Config.baseUrl + '/file/upload',
      fieldName: 'file',
      maxFileSize: 5 * 1024 * 1024,
      allowedFileTypes: ['image/*'],
      meta: {
        Authorization: `Bearer ${localStorage.getItem("token") || ""}`,
      },
      customInsert(res, insertFn) {
        if (res.code === 200 && res.data) {
          insertFn(Config.baseUrl + '/' + res.data)
        } else {
          ElMessage.error('上传失败')
        }
      }
    }
  }
};

// 级别选项
const levelOptions = [
  { label: '国家级', value: '国家级' },
  { label: '省级', value: '省级' },
  { label: '市级', value: '市级' },
  { label: '县级', value: '县级' }
];

// 获取传承人列表
const getList = async () => {
  try {
    const res = await http.get("/inheritor/list", { params: params.value });
    if (res.code === 200) {
      tableData.value = res.data.list;
      total.value = res.data.total;
    }
  } catch (error) {
    console.error("获取传承人列表失败:", error);
  }
};

// 获取分类列表
const getCategoryList = async () => {
  try {
    const res = await http.get("/ichType/list");
    if (res.code === 200) {
      categoryList.value = res.data;
    }
  } catch (error) {
    console.error("获取分类列表失败:", error);
  }
};

// 搜索
const handleSearch = () => {
  params.value.pageNum = 1;
  getList();
};

// 重置
const handleReset = () => {
  params.value = { ...initParams };
  getList();
};

// 新增
const handleAdd = () => {
  isEdit.value = false;
  dialogTitle.value = "新增传承人";
  form.value = { ...initForm };
  imageUrl.value = "";
  visible.value = true;
  // 重置编辑器内容
  if (editorRef.value) {
    editorRef.value.setHtml("");
  }
};

// 编辑
const handleEdit = (row) => {
  isEdit.value = true;
  dialogTitle.value = "编辑传承人";
  form.value = { ...row };
  imageUrl.value = getImageUrl(row.avatar);
  visible.value = true;
  // 设置编辑器内容
  if (editorRef.value) {
    editorRef.value.setHtml(row.description || "");
  }
};

// 删除
const delRow = async (id) => {
  try {
    const res = await http.delete(`/inheritor/${id}`);
    if (res.code === 200) {
      ElMessage.success("删除成功");
      getList();
    }
  } catch (error) {
    console.error("删除失败:", error);
    ElMessage.error("删除失败");
  }
};

// 提交表单
const submitForm = async () => {
  try {
    // 获取编辑器内容
    if (editorRef.value) {
      form.value.description = editorRef.value.getHtml();
    }

    let res;
    if (isEdit.value) {
      res = await http.put("/inheritor", form.value);
    } else {
      res = await http.post("/inheritor", form.value);
    }

    if (res.code === 200) {
      ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
      visible.value = false;
      getList();
    }
  } catch (error) {
    console.error("保存失败:", error);
    ElMessage.error("保存失败");
  }
};

// 关闭弹窗
const handleClose = () => {
  visible.value = false;
};

// 处理图片上传成功
const handleAvatarSuccess = (res) => {
  if (res.code === 200) {
    form.value.avatar = res.data;
    imageUrl.value = getImageUrl(res.data);
  } else {
    ElMessage.error("上传失败");
  }
};

// 图片上传前验证
const beforeAvatarUpload = (file) => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png" || file.type === "image/jpg";
  const isLt2M = file.size / 1024 / 1024 < 2;

  if (!isJPG) {
    ElMessage.error("上传头像图片只能是 JPG/JPEG/PNG 格式!");
  }
  if (!isLt2M) {
    ElMessage.error("上传头像图片大小不能超过 2MB!");
  }
  return isJPG && isLt2M;
};

// 页面大小变化
const handleSizeChange = (val) => {
  params.value.pageSize = val;
  getList();
};

// 当前页码变化
const handleCurrentChange = (val) => {
  params.value.pageNum = val;
  getList();
};

// 组件卸载前销毁编辑器
onBeforeUnmount(() => {
  if (editorRef.value) {
    editorRef.value.destroy();
  }
});

// 编辑器创建成功
const handleEditorCreated = (editor) => {
  editorRef.value = editor;
};

onMounted(() => {
  getList();
  getCategoryList();
});
</script>

<template>
  <div class="container">
    <header class="header">
      <div class="title">传承人管理</div>
    </header>

    <main>
      <!-- 工具栏 -->
      <div class="toolbar">
        <el-button type="primary" :icon="Plus" @click="handleAdd" v-if="hasPermission('inheritor', '新增')">新增</el-button>
      </div>

      <!-- 搜索条件 -->
      <div class="search-container">
        <el-form inline>
          <el-form-item label="传承人姓名">
            <el-input v-model="params.name" placeholder="请输入姓名" />
          </el-form-item>

          <el-form-item label="级别">
            <el-select v-model="params.level" placeholder="请选择级别">
              <el-option label="全部" value="" />
              <el-option v-for="option in levelOptions" :key="option.value" :label="option.label" :value="option.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
            <el-button type="warning" :icon="Refresh" @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格 -->
      <el-table :data="tableData" border>
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="传承人姓名" width="150" />
        <el-table-column prop="avatar" label="头像" width="100">
          <template #default="scope">
            <el-image :src="getImageUrl(scope.row.avatar)" style="width: 40px; height: 40px" fit="cover" />
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100" />
        <el-table-column prop="title" label="称号" width="180" show-overflow-tooltip />
        <el-table-column prop="region" label="地区" width="150" />
        <el-table-column prop="intro" label="简介" show-overflow-tooltip />
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column prop="updateTime" label="更新时间" width="180" />
        <el-table-column label="操作" fixed="right" width="180">
          <template #default="scope">
            <el-button v-if="hasPermission('inheritor', '编辑')" type="primary" :icon="Edit" @click="handleEdit(scope.row)" size="small">编辑</el-button>
            <el-popconfirm
              v-if="hasPermission('inheritor', '删除')"
              title="您确定要删除吗?"
              @confirm="delRow(scope.row.id)"
            >
              <template #reference>
                <el-button type="danger" :icon="Delete" size="small">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="params.pageNum"
          v-model:page-size="params.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="sizes, prev, pager, next"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </main>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="visible"
      :title="dialogTitle"
      width="700px"
      :before-close="handleClose"
    >
      <el-form :model="form" label-width="100px">
        <el-form-item label="传承人姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入传承人姓名" />
        </el-form-item>

        <el-form-item label="头像" prop="avatar">
          <el-upload
            class="avatar-uploader"
            :action="uploadUrl"
            :headers="uploadData.headers"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <el-image
              v-if="imageUrl"
              :src="imageUrl"
              style="width: 120px; height: 120px"
              fit="cover"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
          </el-upload>
        </el-form-item>

        <el-form-item label="级别" prop="level">
          <el-select v-model="form.level" placeholder="请选择级别">
            <el-option v-for="option in levelOptions" :key="option.value" :label="option.label" :value="option.value" />
          </el-select>
        </el-form-item>

        <el-form-item label="称号" prop="title">
          <el-input v-model="form.title" placeholder="请输入称号" />
        </el-form-item>

        <el-form-item label="地区" prop="region">
          <el-input v-model="form.region" placeholder="请输入地区" />
        </el-form-item>

        <el-form-item label="所属分类" prop="categoryId">
          <el-select v-model="form.categoryId" placeholder="请选择所属分类">
            <el-option
              v-for="category in categoryList"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="简介" prop="intro">
          <el-input
            type="textarea"
            v-model="form.intro"
            :autosize="{ minRows: 2, maxRows: 4 }"
            placeholder="请输入简介"
          />
        </el-form-item>

        <el-form-item label="详细介绍" prop="description">
          <div style="width: 100%; border: 1px solid #ccc">
            <Toolbar
              style="border-bottom: 1px solid #ccc"
              :editor="editorRef"
              :defaultConfig="toolbarConfig"
            />
            <Editor
              style="height: 300px; overflow-y: hidden"
              :defaultConfig="editorConfig"
              v-model="form.description"
              @created="handleEditorCreated"
            />
          </div>
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.container {
  width: 100%;
  height: 100%;
  background-color: #fff;
  border-radius: 4px;
  overflow: hidden;

  .header {
    padding: 16px;
    border-bottom: 1px solid #e4e7ed;

    .title {
      font-size: 18px;
      font-weight: 500;
      color: #303133;
    }
  }

  main {
    padding: 16px;

    .toolbar {
      margin-bottom: 16px;
    }

    .search-container {
      padding: 16px;
      background-color: #f5f7fa;
      border-radius: 4px;
      margin-bottom: 16px;
    }

    .pagination-container {
      margin-top: 16px;
      display: flex;
      justify-content: flex-end;
    }
  }
}

// 头像上传样式
.avatar-uploader {
  width: 120px;
  height: 120px;
  .avatar-uploader-icon {
    font-size: 28px;
    color: #c0c4cc;
    width: 120px;
    height: 120px;
    line-height: 120px;
    text-align: center;
    border: 1px dashed #dcdfe6;
    border-radius: 4px;
    cursor: pointer;
    display: block;
  }
}

// 编辑器样式
:deep(.w-e-toolbar) {
  padding: 0 10px;
}

:deep(.w-e-text-container) {
  height: 300px !important;
}
</style>